package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.enums.SoundType;
import com.tanhua.model.mongo.UserSound;
import com.tanhua.model.mongo.UserSoundTime;
import com.tanhua.model.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Random;

/**
 * @Description: test
 * @Create by: 熊孩子
 * @Date: 2021/12/11 14:10
 */
@DubboService
public class UserSoundApiImpl implements UserSoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    //保存语音数据，并保存/修改发送次数
    @Override
    public void save(UserSound userSound) {
        userSound.setSid(idWorker.getNextId("sound"));
        mongoTemplate.save(userSound);
        if (userSound != null) {
            //保存或修改剩余次数
            Query query = Query.query(Criteria.where("userId").is(userSound.getUserId())
                    .and("date").is(userSound.getDate()).and("soundType").is(SoundType.SEND.getType()));
            UserSoundTime userSoundTime = mongoTemplate.findOne(query, UserSoundTime.class);
            if (userSoundTime == null) {
                //保存剩余发送次数
                userSoundTime = new UserSoundTime();
                userSoundTime.setUserId(userSound.getUserId());
                userSoundTime.setDate(userSound.getDate());
                userSoundTime.setResidueCount(9);
                userSoundTime.setSoundType(SoundType.SEND.getType());
                mongoTemplate.save(userSoundTime);
            } else {
                //修改剩余发送次数
                Update update = new Update();
                update.inc("residueCount", -1);
                mongoTemplate.updateFirst(query, update, UserSoundTime.class);
            }

        }
    }

    //随机构造1条语音数据排除自己的语音
    @Override
    public UserSound randomSound(Long userId) {
        Query query = Query.query(Criteria.where("userId").ne(userId));
        long count = mongoTemplate.count(query, UserSound.class);
        int starNum = new Random().nextInt((int) count);
        query.skip(starNum).limit(1);
        return mongoTemplate.findOne(query, UserSound.class);
    }

    //删除语音
    @Override
    public void delete(ObjectId id) {
        mongoTemplate.remove(Query.query(Criteria.where("id").is(id)), UserSound.class);
    }
}
